﻿using HtmlAgilityPack;
using Microsoft.Data.Sqlite;
using SQLitePCL;
using System.Collections.Generic;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using static System.Net.WebRequestMethods;
using File = System.IO.File;
using HtmlDocument = HtmlAgilityPack.HtmlDocument;

namespace CopyXl
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //文件选择框
            // 创建并配置OpenFileDialog
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.InitialDirectory = "c:\\"; // 初始目录
                openFileDialog.Filter = "所有文件 (*.*)|*.*|文本文件 (*.txt)|*.txt"; // 文件过滤
                openFileDialog.FilterIndex = 1; // 默认过滤器
                openFileDialog.RestoreDirectory = true;

                // 打开文件选择对话框
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // 获取选中的文件路径
                    string filePath = openFileDialog.FileName;
                    button1.Text = filePath;
                }
            }


        }

        private async void button2_Click(object sender, EventArgs e)
        {

            try
            {
                //https://ltyl.szptwy.net/bt/?p=1 注意 拼接字符只追加数字，输入要注意/?p=  这个写上去
                string url1 = textBox1.Text;
                int startNum = 1;
                int redNum = 1;
                if (!string.IsNullOrEmpty(tbxStartNum.Text) && !string.IsNullOrEmpty(tbReadNum.Text))
                {
                    startNum = int.Parse(tbxStartNum.Text);
                    redNum = int.Parse(tbReadNum.Text);
                }
                int count = 0;
                for (int i = 0; i < redNum; i++)
                {
                    try
                    {
                        var url = url1 + startNum;
                        lblCurNum.Text = url;
                        startNum++;
                        HttpClientHandler handler = new HttpClientHandler
                        {
                            ServerCertificateCustomValidationCallback = (HttpRequestMessage request, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true
                        };
                        // 使用 HttpClient 下载网页内容
                        HttpClient client = new HttpClient(handler);
                        var response = await client.GetStringAsync(url);

                        // 解析 HTML https://ltyl.szptwy.net/bt/?p=1
                        var htmlDoc = new HtmlDocument();
                        htmlDoc.LoadHtml(response);


                        // 查找 Magnet 链接
                        var magnetLinks = new List<string>();
                        foreach (var link in htmlDoc.DocumentNode.SelectNodes("//a[starts-with(@href, 'magnet:')]"))
                        {
                            var hrefValue = link.GetAttributeValue("href", string.Empty);
                            if (!string.IsNullOrEmpty(hrefValue))
                            {
                                magnetLinks.Add(hrefValue);
                                Console.WriteLine(hrefValue);
                            }
                        }

                        // 输出结果
                        Console.WriteLine("找到的 Magnet 链接:");
                        foreach (var magnet in magnetLinks)
                        {
                            //如果txt存在就添加，若不存在，先生成再添加
                            if (File.Exists("magnet.txt"))
                            {
                                using (StreamWriter sw = File.AppendText("magnet.txt"))
                                {
                                    sw.WriteLine(magnet);
                                }
                            }
                            else
                            {
                                using (StreamWriter sw = File.CreateText("magnet.txt"))
                                {
                                    sw.WriteLine(magnet);
                                }
                            }
                        }
                        count = count + magnetLinks.Count;
                    }
                    catch (Exception ex)
                    {
                        tbxLog.AppendText($"当前页:{startNum}--异常:{ex.Message}");
                    }

                }
                MessageBox.Show("添加成功" + count);

            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex}");
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            //magnet:?xt
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //读取文件 每30行生成一个新文件，文件序号从1开始
            int count = 0;
            //读取磁链文件夹
            Task.Run(() =>
            {
                int countCf = 0;
                try
                {
                    // 获取“磁链”文件夹路径
                    string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "磁链");
                    if (!Directory.Exists(folderPath))
                    {
                        MessageBox.Show("未找到“磁链”文件夹");
                        return;
                    }

                    // 获取所有文件
                    string[] files = Directory.GetFiles(folderPath);

                    // 使用 HashSet 提高查重效率
                    HashSet<string> magnetLinks = new HashSet<string>();

                    foreach (string file in files)
                    {
                        using (StreamReader sr = new StreamReader(file))
                        {
                            while (!sr.EndOfStream)
                            {
                                string line = sr.ReadLine();
                                if (!string.IsNullOrWhiteSpace(line))
                                {
                                    if (!magnetLinks.Add(line))
                                    {
                                        countCf++;
                                    }
                                }
                            }
                        }
                    }
                    var name = "磁链";
                    if (!string.IsNullOrEmpty(textBox2.Text))
                    {
                        name = textBox2.Text;
                    }
                    //遍历magnetLinks,每30行生成一个新文件
                    foreach (var magnet in magnetLinks)
                    {
                        if (count % 30 == 0)
                        {
                            //存放到磁链文件夹
                            name = textBox2.Text;
                            string fileName = $"磁链\\{name}{count / 30 + 1}.txt";
                            using (StreamWriter sw = File.AppendText(fileName))
                            {
                                sw.WriteLine(magnet);
                            }
                        }
                        else
                        {
                            string fileName = $"磁链\\{name}{count / 30 + 1}.txt";
                            using (StreamWriter sw = File.AppendText(fileName))
                            {
                                sw.WriteLine(magnet);
                            }
                        }
                        count++;
                    }




                    // 最后在 UI 线程弹出消息框
                    this.Invoke(new Action(() =>
                    {
                        MessageBox.Show($"读取写入成功：{magnetLinks.Count} 条，重复条数：{countCf}");
                    }));
                }
                catch (Exception ex)
                {
                    // 错误信息也在 UI 线程提示
                    this.Invoke(new Action(() =>
                    {
                        MessageBox.Show("处理失败：" + ex.Message);
                    }));
                }
            });


        }

        private async void btnDownP_Click(object sender, EventArgs e)
        {
            try
            {
                //https://ltyl.szptwy.net/bt/?p=1 注意 拼接字符只追加数字，输入要注意/?p=  这个写上去
                string url1 = textBox1.Text;
                int startNum = 1;
                int redNum = 1;
                int countPic = 0;
                if (!string.IsNullOrEmpty(tbxStartNum.Text) && !string.IsNullOrEmpty(tbReadNum.Text))
                {
                    startNum = int.Parse(tbxStartNum.Text);
                    redNum = int.Parse(tbReadNum.Text);
                }
                int count = 0;
                for (int i = 0; i < redNum; i++)
                {
                    try
                    {
                        var url = url1 + startNum;
                        lblCurNum.Text = url;
                        startNum++;
                        HttpClientHandler handler = new HttpClientHandler
                        {
                            ServerCertificateCustomValidationCallback = (HttpRequestMessage request, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true
                        };
                        // 使用 HttpClient 下载网页内容
                        HttpClient client = new HttpClient(handler);
                        var response = await client.GetStringAsync(url);

                        // 解析 HTML https://ltyl.szptwy.net/bt/?p=1
                        // <a href="?s=L3ZpZXc/aWQ9ZjEzYWY3MGExOGZhMDg5NWY5OTJkM2JmNzk3YmUxNTRmYjAzNTUwNA"
                        // title="PRED-771 倒れたつむぎ先生を介抱して家に送っ【AI破解版】" target="_blank">		
                        // <span style="color: green;"><b>IMG</b></span>      PRED-771 倒れたつむぎ先生を介抱して家に送っ【AI破解版】  </a>
                        var htmlDoc = new HtmlDocument();
                        htmlDoc.LoadHtml(response);
                        //解析html中是否包含span标签，并且span标签的style包含color: green;
                        var bNodes = htmlDoc.DocumentNode.SelectNodes("//span[@style='color: green;']/..");
                        string aval = "";
                        if (bNodes != null)
                        {
                            //打开b标签的同级元素a标签的链接
                            foreach (var bNode in bNodes)
                            {
                                try
                                {
                                    var aNode = bNode.ParentNode;
                                    if (aNode != null)
                                    {
                                        //查找a标签
                                        var aNodes = aNode.SelectNodes("a");
                                        if (aNodes != null)
                                        {
                                            foreach (var aNode1 in aNodes)
                                            {

                                                //\t\t\t\t\t\t\t\t  \t\t\t\t\t        \t  \t\t\t\t  \t\t\t\t\t
                                                //<a href=\"?s=L3ZpZXc/aWQ9YTBmNGIwZDBhMmRiNzg0NDY3Nzg0MDE4ZDE1OWU4NDY5YjE0YjBmMA\" title=\"SONE-712 脚にぶっかけ、尻にぶっかけ、毎朝し【AI破解版】\" target=\"_blank\">\t\t
                                                //<span style=\"color: green;\"><b>IMG</b></span>      SONE-712 脚にぶっかけ、尻にぶっかけ、毎朝し【AI破解版】  </a>      \t\t\t
                                                //获取 hraf的值
                                                aval = aNode1.Attributes["href"].Value;
                                                if (!string.IsNullOrEmpty(aval))
                                                {
                                                    //https://ltyl.szptwy.net/bt/?s=L3ZpZXc/aWQ9YTBmNGIwZDBhMmRiNzg0NDY3Nzg0MDE4ZDE1OWU4NDY5YjE0YjBmMA
                                                    //拼接
                                                    string aHrefLink = "https://ltyl.szptwy.net/bt/" + aval;
                                                    //进入此链接
                                                    HttpClientHandler handler1 = new HttpClientHandler
                                                    {
                                                        ServerCertificateCustomValidationCallback = (HttpRequestMessage request, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true
                                                    };
                                                    HttpClient client1 = new HttpClient(handler1);
                                                    var response1 = await client1.GetStringAsync(aHrefLink);
                                                    var htmlDoc1 = new HtmlDocument();
                                                    htmlDoc1.LoadHtml(response1);
                                                    var imgNodes = htmlDoc1.DocumentNode.SelectNodes("//img");
                                                    if (imgNodes != null)
                                                    {
                                                        foreach (var imgNode in imgNodes)
                                                        {
                                                            try
                                                            {
                                                                //获取img标签的src的值
                                                                string src = imgNode.Attributes["src"].Value;
                                                                //src中必须是是jpg或者png格式
                                                                if (!src.Contains(".jpg") && !src.Contains(".png"))
                                                                {
                                                                    continue;
                                                                }
                                                                //创建一个文件夹，文件夹名为aNode1中的title的值
                                                                string tval = "";
                                                                tval = aNode1.Attributes["title"].Value;
                                                                if (!string.IsNullOrEmpty(tval))
                                                                {
                                                                    string pathdDownload = Environment.CurrentDirectory + "\\download\\" + tval;
                                                                    //使用using 语句创建一个文件夹
                                                                    if (!Directory.Exists(pathdDownload))
                                                                    {
                                                                        Directory.CreateDirectory(pathdDownload);
                                                                    }
                                                                    //使用using创建一个txt文件，文件名为url2中的title的值,存入到创建的文件夹
                                                                    try
                                                                    {
                                                                        if (!File.Exists(pathdDownload + "\\" + tval + ".txt"))
                                                                        {
                                                                            //创建一个txt文件，文件名为url2中的title的值,存入到创建的文件夹
                                                                            using (StreamWriter sw = File.CreateText(pathdDownload + "\\" + tval + ".txt"))
                                                                            {
                                                                                //获取当前这个页面的磁链
                                                                                // 查找 Magnet 链接
                                                                                var magnetLinks = new List<string>();
                                                                                foreach (var link in htmlDoc1.DocumentNode.SelectNodes("//a[starts-with(@href, 'magnet:')]"))
                                                                                {
                                                                                    var hrefValue = link.GetAttributeValue("href", string.Empty);
                                                                                    if (!string.IsNullOrEmpty(hrefValue))
                                                                                    {
                                                                                        magnetLinks.Add(hrefValue);
                                                                                    }
                                                                                }
                                                                                foreach (var magnet in magnetLinks)
                                                                                {
                                                                                    sw.WriteLine(magnet);
                                                                                }
                                                                            }
                                                                        }



                                                                    }
                                                                    catch (Exception ex)
                                                                    {
                                                                        tbxLog.AppendText($"当前页:{startNum}--异常:{ex.Message}");
                                                                    }

                                                                    string imageUrl = src;
                                                                    string savePath = pathdDownload + src;
                                                                    try
                                                                    {
                                                                        using (WebClient client2 = new WebClient())
                                                                        {
                                                                            // 模拟浏览器请求
                                                                            client2.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
                                                                            client2.Headers.Add("Referer", aHrefLink);

                                                                            try
                                                                            {
                                                                                //https://qpic.ws/images/2025/05/09/HQmc7C.jpg 截取掉https://qpic.ws/images/
                                                                                string imageUrl2 = imageUrl.Substring(23);
                                                                                //替换掉/为-
                                                                                imageUrl2 = imageUrl2.Replace("/", "-");
                                                                                client2.DownloadFile(imageUrl, pathdDownload + "\\" + imageUrl2);
                                                                                countPic++;
                                                                                tbxLog.AppendText($"download:{countPic}----{imageUrl2}\r\n");
                                                                                //加换行符
                                                                            }
                                                                            catch (WebException ex)
                                                                            {
                                                                                //重新加载html
                                                                                Console.WriteLine("下载失败: " + ex.Message);

                                                                                if (ex.Response != null)
                                                                                {
                                                                                    using (var reader = new System.IO.StreamReader(ex.Response.GetResponseStream()))
                                                                                    {
                                                                                        Console.WriteLine("服务器响应:");
                                                                                        Console.WriteLine(reader.ReadToEnd());
                                                                                    }
                                                                                }
                                                                            }
                                                                        }

                                                                    }
                                                                    catch (Exception ex)
                                                                    {
                                                                        tbxLog.AppendText(ex.Message);
                                                                    }


                                                                }


                                                            }
                                                            catch (Exception ex)
                                                            {
                                                                tbxLog.AppendText($"当前页:{startNum}--异常:{ex.Message}");
                                                            }
                                                        }
                                                    }
                                                }
                                            }


                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    tbxLog.AppendText($"当前页:{startNum}--异常:{ex.Message}");
                                }

                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        tbxLog.AppendText($"当前页:{startNum}--异常:{ex.Message}");
                    }
                }
                MessageBox.Show("下载完成");
            }
            catch (Exception ex)
            {
                tbxLog.AppendText($"当前页:--异常:{ex.Message}");
            }


        }

        private void button5_Click(object sender, EventArgs e)
        {
            // 创建异步任务
            Task.Run(() =>
            {
                int countCf = 0;
                try
                {
                    // 获取“磁链”文件夹路径
                    string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "磁链");
                    if (!Directory.Exists(folderPath))
                    {
                        MessageBox.Show("未找到“磁链”文件夹");
                        return;
                    }

                    // 获取所有文件
                    string[] files = Directory.GetFiles(folderPath);

                    // 使用 HashSet 提高查重效率
                    HashSet<string> magnetLinks = new HashSet<string>();

                    foreach (string file in files)
                    {
                        using (StreamReader sr = new StreamReader(file))
                        {
                            while (!sr.EndOfStream)
                            {
                                string line = sr.ReadLine();
                                if (!string.IsNullOrWhiteSpace(line))
                                {
                                    if (!magnetLinks.Add(line))
                                    {
                                        countCf++;
                                    }
                                }
                            }
                        }
                    }

                    // 写入新的文件
                    string outputPath = Path.Combine(folderPath, "磁链.txt");
                    using (StreamWriter sw = new StreamWriter(outputPath))
                    {
                        foreach (string magnetLink in magnetLinks)
                        {
                            sw.WriteLine(magnetLink);
                        }
                    }

                    // 最后在 UI 线程弹出消息框
                    this.Invoke(new Action(() =>
                    {
                        MessageBox.Show($"读取写入成功：{magnetLinks.Count} 条，重复条数：{countCf}");
                    }));
                }
                catch (Exception ex)
                {
                    // 错误信息也在 UI 线程提示
                    this.Invoke(new Action(() =>
                    {
                        MessageBox.Show("处理失败：" + ex.Message);
                    }));
                }
            });
        }


        private async void button6_Click(object sender, EventArgs e)
        {
            try
            {
                //https://ltyl.szptwy.net/bt/?p=1 注意 拼接字符只追加数字，输入要注意/?p=  这个写上去
                int scount = 0;
                string url1 = textBox1.Text;
                int startNum = 1;
                int redNum = 1;
                if (!string.IsNullOrEmpty(tbxStartNum.Text) && !string.IsNullOrEmpty(tbReadNum.Text))
                {
                    startNum = int.Parse(tbxStartNum.Text);
                    redNum = int.Parse(tbReadNum.Text);
                }
                int count = 0;
                for (int i = 0; i < redNum; i++)
                {
                    try
                    {
                        var url = url1 + startNum;
                        lblCurNum.Text = url;
                        startNum++;
                        HttpClientHandler handler = new HttpClientHandler
                        {
                            ServerCertificateCustomValidationCallback = (HttpRequestMessage request, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true
                        };
                        // 使用 HttpClient 下载网页内容
                        HttpClient client = new HttpClient(handler);
                        var response = await client.GetStringAsync(url);

                        // 解析 HTML https://ltyl.szptwy.net/bt/?p=1
                        var htmlDoc = new HtmlDocument();
                        htmlDoc.LoadHtml(response);

                        // 查找 Magnet 链接
                        var magnetLinks = new List<string>();

                        //查找所有的a标签
                        var links = htmlDoc.DocumentNode.SelectNodes("//a[@href]");
                        // 遍历所有链接
                        foreach (var link in links)
                        {
                            var ti = link.GetAttributeValue("title", "");
                            //如果a标签的title包含textBox2的值就获取此a标签的上级元素
                            if (ti.Contains(textBox2.Text))
                            {
                                //html的结构是一个tr中有多个td，我现在获取到了第二个td
                                var td2 = link.ParentNode;
                                //我想要获取第4个td元素
                                var td3 = td2.NextSibling;
                                var td4 = td3.NextSibling;
                                //获取td4中的a标签，并且a标签的href包含magnet链接
                                var a = td4.ChildNodes.OfType<HtmlNode>().FirstOrDefault(x => x.GetAttributeValue("href", "").Contains("magnet"));
                                if (a != null)
                                {
                                    //获取a标签的href属性
                                    var magnet = a.GetAttributeValue("href", "");
                                    //如果magnet不为空，就添加到listView1中
                                    if (!string.IsNullOrEmpty(magnet))
                                    {
                                        magnetLinks.Add(magnet);
                                        scount++;
                                        tbxLog.AppendText("Serch --" + scount + "\r\n");
                                    }
                                }
                            }
                        }




                        // 输出结果
                        Console.WriteLine("找到的 Magnet 链接:");
                        foreach (var magnet in magnetLinks)
                        {
                            //如果txt存在就添加，若不存在，先生成再添加
                            var name = textBox2.Text + ".txt";

                            if (File.Exists(name))
                            {
                                using (StreamWriter sw = File.AppendText(name))
                                {
                                    sw.WriteLine(magnet);
                                }
                            }
                            else
                            {
                                using (StreamWriter sw = File.CreateText(name))
                                {
                                    sw.WriteLine(magnet);
                                }
                            }
                        }
                        count = count + magnetLinks.Count;
                    }
                    catch (Exception ex)
                    {
                        tbxLog.AppendText($"当前页:{startNum}--异常:{ex.Message}");
                    }

                }
                MessageBox.Show("添加成功" + count);

            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex}");
            }
        }

        private async void button7_Click(object sender, EventArgs e)
        {
            try
            {
                //https://ltyl.szptwy.net/bt/?p=1 注意 拼接字符只追加数字，输入要注意/?p=  这个写上去
                var guid = Guid.NewGuid().ToString() + ".txt";

                string url1 = textBox1.Text;
                int startNum = 1;
                int redNum = 1;
                if (!string.IsNullOrEmpty(tbxStartNum.Text) && !string.IsNullOrEmpty(tbReadNum.Text))
                {
                    startNum = int.Parse(tbxStartNum.Text);
                    redNum = int.Parse(tbReadNum.Text);
                }
                int count = 0;
                for (int i = 0; i < redNum; i++)
                {
                    try
                    {
                        var url = url1 + startNum;
                        lblCurNum.Text = url;
                        startNum++;
                        HttpClientHandler handler = new HttpClientHandler
                        {
                            ServerCertificateCustomValidationCallback = (HttpRequestMessage request, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true
                        };
                        // 使用 HttpClient 下载网页内容
                        HttpClient client = new HttpClient(handler);
                        var response = await client.GetStringAsync(url);

                        // 解析 HTML https://ltyl.szptwy.net/bt/?p=1
                        var htmlDoc = new HtmlDocument();
                        htmlDoc.LoadHtml(response);


                        // 查找 Magnet 链接
                        var magnetLinks = new Dictionary<string, string>();
                        foreach (var link in htmlDoc.DocumentNode.SelectNodes("//a[starts-with(@href, 'magnet:')]"))
                        {
                            var hrefValue = link.GetAttributeValue("href", string.Empty);
                            //获取title
                            //获取ling的上级元素的上一个元素
                            var td = link.ParentNode.PreviousSibling.PreviousSibling;
                            //获取td中的a标签
                            var a = td.InnerText;
                            //去除\t
                            a = a.Replace("\t", "");
                            if (!string.IsNullOrEmpty(a))
                            {
                                magnetLinks.TryAdd(a, hrefValue);
                            }

                        }

                        // 输出结果
                        Console.WriteLine("找到的 Magnet 链接:");
                        foreach (var magnet in magnetLinks)
                        {
                            //如果txt存在就添加，若不存在，先生成再添加
                            if (File.Exists(guid))
                            {
                                using (StreamWriter sw = File.AppendText(guid))
                                {
                                    sw.WriteLine($"key:{magnet.Key}val:{magnet.Value}");
                                }
                            }
                            else
                            {
                                using (StreamWriter sw = File.CreateText(guid))
                                {
                                    sw.WriteLine($"key:{magnet.Key}val:{magnet.Value}");
                                }
                            }
                        }
                        count = count + magnetLinks.Count;
                    }
                    catch (Exception ex)
                    {
                        tbxLog.AppendText($"当前页:{startNum}--异常:{ex.Message}");
                    }

                }
                MessageBox.Show("添加成功" + count);

            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex}");
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            try
            {
                const string dbFile = "magnet.db";

                // 1️⃣ 生成连接字符串：若文件不存在自动创建
                var connectionString = new SqliteConnectionStringBuilder
                {
                    DataSource = dbFile,
                    Mode = SqliteOpenMode.ReadWriteCreate
                }.ToString();

                // 2️⃣ 打开连接
                using var conn = new SqliteConnection(connectionString);
                conn.Open();

                // 3️⃣ 建表（幂等）
                const string createTableSql =
        "CREATE TABLE IF NOT EXISTS magnet (" +
        "id     INTEGER PRIMARY KEY AUTOINCREMENT, " +
        "magnet TEXT    NOT NULL, " +
        "title  TEXT, " +
        "`time` TEXT" +          // 给 time 加反引号，避免关键字冲突
        ");";


                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = createTableSql;
                    cmd.ExecuteNonQuery();
                }
                //读取magnet.txt,批量写入数据库
                string[] lines = File.ReadAllLines("magnet.txt");
                tbxLog.AppendText("开始写入数据库");
                using var tran = conn.BeginTransaction();

                foreach (var line in lines)
                {
                    if (!line.Contains("key") || !line.Contains("val")) continue;

                    var key = line.Split("key:")[1].Split("val:")[0];
                    var val = line.Split("val:")[1];

                    using var cmd = conn.CreateCommand();
                    cmd.CommandText = "INSERT INTO magnet (magnet, title, `time`) VALUES ($val, $key, $time)";
                    cmd.Parameters.AddWithValue("$val", val);
                    cmd.Parameters.AddWithValue("$key", key);
                    cmd.Parameters.AddWithValue("$time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    cmd.ExecuteNonQuery();
                }

                tran.Commit();

                MessageBox.Show("添加成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex}");
            }


        }
        Dictionary<string, string> magnetLinks = new Dictionary<string, string>();

        private void button9_Click(object sender, EventArgs e)
        {
            magnetLinks.Clear();
            //读取DBFile文件夹txt文件
            string[] files = Directory.GetFiles("DBFile");
            foreach (var file in files)
            {
                //读取txt文件
                string[] lines = File.ReadAllLines(file);
                foreach (var line in lines)
                {
                    if (!line.Contains("key") || !line.Contains("val")) continue;
                    var key = line.Split("key:")[1].Split("val:")[0];
                    var val = line.Split("val:")[1];
                    //添加到字典
                    magnetLinks.TryAdd(key, val);
                }
            }
            MessageBox.Show(magnetLinks.Count.ToString());

        }

        private void button10_Click(object sender, EventArgs e)
        {
            var sxname = textBox2.Text;
            int count = 0;
            try
            {
                //从magnetLinks查询包含sxname的key
                foreach (var item in magnetLinks)
                {
                    if (item.Key.Contains(sxname))
                    {
                        //输出到txt
                        using (StreamWriter sw = File.AppendText($"DBFile\\筛选\\{sxname}.txt"))
                        {
                            sw.WriteLine($"{item.Value}");
                        }
                        count++;
                    }
                }
                MessageBox.Show(count.ToString());
            }
            catch (Exception ex)
            {
                tbxLog.AppendText($"{ex}");
            }
        }
    }

}


